package ms.core.tool;

import java.io.InputStream;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.Configurator;

public class Log4j2Tool {
	private static boolean inited = false;
	private static String configFile = "/config/log4j2.xml"; // 默认log42j配置文件

	private static void init(String conf) {
		try {
			if (inited) return;
			InputStream in = StreamTool.loadFileToStream(Log4j2Tool.class, conf);
			ConfigurationSource source = new ConfigurationSource(in);
			Configurator.initialize(null, source);
			in.close();
			inited = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void setConfile(String fileName) {
		configFile = fileName;
	}

	public static void debug(Class<?> cls, String msg) {
		init(configFile);
		Logger logger = LogManager.getLogger(cls);
		logger.debug(msg);
	}

	public static void info(Class<?> cls, String info) {
		init(configFile);
		Logger logger = LogManager.getLogger(cls);
		logger.info(info);
	}

	public static void error(Class<?> cls, String err) {
		init(configFile);
		Logger logger = LogManager.getLogger(cls);
		logger.error(err);
	}

	public static void error(Class<?> cls, String msg, Throwable e) {
		init(configFile);
		Logger logger = LogManager.getLogger(cls);
		logger.error(msg, e);
	}

	public static void error(Class<?> cls, Throwable e) {
		init(configFile);
		Logger logger = LogManager.getLogger(cls);
		logger.error(e);
	}

	public static void main(String[] args) {
		Log4j2Tool.init("/config/log4j2.xml");
		Log4j2Tool.debug(Log4j2Tool.class, "this is a debug message");
		Log4j2Tool.info(Log4j2Tool.class, "this is a notify info");
		Log4j2Tool.error(Log4j2Tool.class, "this is a error message");
		try {
			int i = 1, b = 0;
			System.out.println(i / b);
		} catch (Exception e) {
			Log4j2Tool.error(Log4j2Tool.class, "非法除法", e);
		}
	}
}
